<?php
namespace control;

// 管理员后台-拆解单
class dismantleClass extends adIndexClass
{
	private const page        = 'dismantle';
	private const table       = 'inventory_dismantle';
	private const tableMx     = 'inventory_dismantle_detail';
	private const tableRecord = 'inventory_record';
	private const title       = '拆解单';
	private const state       = ['草稿', '待确认', '已确认'];

    /**
     * 字段初始化
     */
    public function fieldInit($fun): array
    {
        switch ($fun) {
            default:
                $tr = [
                    'orderNo'          => [
                        'name'  => '单据编号',
                        'width' => 200,
                        'sort' => 1,
                    ],
                    'name' => [
                        'name'  => "组合件",
                        'width' => 150,
                    ],
                    'model'  => [
                        'name'  => "规格型号",
                        'width' => 200,
                    ],
                    'unit'  => [
                        'name'  => "单位",
                        'width' => 150,
                    ],
                    'num'  => [
                        'name'  => "数量",
                        'width' => 150,
                        'sort' => 1,
                    ],
                    'materialCost'         => [
                        'name'  => '组合件成本（' . static::$unit . '）',
                        'width' => 180,
                        'sort' => 1,
                    ],
                    'fee'          => [
                        'name'  => '拆解费用（' . static::$unit . '）',
                        'width' => 180,
                        'sort' => 1,
                    ],
                    'dismantleCost'          => [
                        'name'  => '拆解成本（' . static::$unit . '）',
                        'width' => 180,
                    ],
                    'orderDate'          => [
                        'name'  => '单据日期',
                        'width' => 180,
                        'sort' => 1,
                    ],
                    'state'          => [
                        'name'  => '状态',
                        'width' => 180,
                    ]
                ];
        }
        return $tr;
    }

    /*列表页-查询条件*/
    public function homeOptions($isAsync = true)
    {
        //生成查询表单
        $html = $this->tableShow([
            [
                [
                    "单据编号" => text(array("name" => "orderNo")),
                    "组合件"   => text(array("name" => "materialName")),
                    "规格型号"   => text(array("name" => "model")),
                ],
                [
                    "单据日期" => text(array("name" => "orderDate", 'laydate' => ['type' => 'date', 'range' => '~'])),
                    "状态" => select(["name" => "state", 'option' => self::state]),
                ]
            ]
        ],1);
        //返回
        if (!$isAsync) {
            return $html;
        } else {
            return json_encode(['html' => $html], 320);
        }
    }

	/**
	 * 列表-查询条件
	 *
	 * @return string
	 */
	public function home(): string
	{
        $html = $this->homeOptions(false);
        //控件
        $button = "";
        $url = root . "control/adIndex.html?cla=" . self::page;
        if ($this->power(self::page, "edit")) {
            $button .= "<span onclick=\"newIframe('" . self::title . "详情','" . $url . "&fun=edit')\" class='spanButton'>新增</span>\n";
        }
        if ($this->power(self::page, "del")) {
            $button .= "<span class='spanButton' onclick=\"layer('{$this->get('cla')}', 'operate', {'act': 'del'})\">删除</span>\n";
        }
		//返回
		return $this->homeFun($this->search($html, layout: 'pop', toolButton: $button));
	}

	/*客户列表-查询结果*/
	public function homeSearch(): string
	{
		//查询结果
		$where = " coid = '" . self::$coid . "' ";
		$and   = search([
			'like' => [
				'name'  => $this->post('materialName'),
				'model' => $this->post('model'),
			],
		]);
		if ($and) {
			$where .= " AND materialId in (SELECT id FROM material WHERE 1=1 $and) ";
		}
		//生成查询语句
		$where .= search([
			"="    => [
				'orderNo' => $this->post('orderNo'),
			],
			"like" => [
				'state' => $this->post('state'),
			],
		]);
		if ($this->post('orderDate')) {
			$where .= self::timeComparison($this->post('orderDate'), 'date', 'orderDate');
		}
        //排序
        $orderBy = $this->listSort(array(
            "search"  => $this->post('list_sort_key') ?: 'time',
            "sort" => $this->post('list_sort') ?: "desc",
            "array"   => array(),
        ));
		$page = $this->page(array("table" => self::table, "where" => $where, "order" => $orderBy['orderBy']));
        //获取自定义字段参数
        $installSearch = $this->installSearch();
        $body          = [];
        //表格控件区
        $liButton = array(
            $this->checkAll("listForm", "listId")
        );
		//获取记录
		$url = root . "control/adIndex.html?cla=" . self::page;
		foreach ($page['array'] as $array) {
			//列表控件
			$dominate     = array(
				"box"    => array("name" => "listId", "value" => $array['id']),
				"detail" => array(
					"title" => self::title . "详情",
					"click" => "newIframe('" . self::title . "详情','" . $url . "&fun=detail&id=" . $array['id'] . "')",
				),
				"edit"   => $array['state'] == '草稿' ? [
					"title" => "编辑",
					"click" => "newIframe('" . self::title . "详情','" . $url . "&fun=edit&id=" . $array['id'] . "')",
				] : [],
			);
			$material      = query('material', " id = '$array[materialId]' ");
            $liButton[] = $this->dominate($dominate);
            //本行初始化
            $row = [];
            foreach ($installSearch['key'] as $key) {
                switch ($key) {
                    case 'num':
                        $row[] = self::lostZero($array['num'], 'numPrecision');
                        break;
                    case 'materialCost':
                    case 'fee':
                        $row[] = self::lostZero($array[$key]);
                        break;
                    case 'dismantleCost':
                        $row[] = self::formattingFigure($array['materialCost']+$array['fee']);
                        break;
                    case 'name':
                    case 'model':
                    case 'unit':
                        $row[] = $material[$key];
                        break;
                    default:
                        $row[] = isset($array[$key]) && $array[$key] ? $array[$key] : '';
                }
            }
            $body[] = $row;
		}
        $totalQuery = find([
            'table'  => self::table,
            'single' => $where,
            'field'  => "ifnull(sum(num),0) as num,ifnull(sum(materialCost),0) as materialCost,ifnull(sum(fee),0) as fee",
        ]);
        $total    = [
            'num'        => self::lostZero($totalQuery['num'], 'numPrecision'),
            'materialCost'        => self::lostZero($totalQuery['materialCost']),
            'fee'        => self::lostZero($totalQuery['fee']),
            'dismantleCost'        => self::formattingFigure($totalQuery['materialCost'] + $totalQuery['fee']),
        ];
        //生成页面
        $li = $this->li(array(
            "body" => $body,
            "install" => $installSearch,
            "button" => array("html" => $liButton),
            "orderBySign" => $orderBy,
            "page" => $page['para'],
            "total"       => $total,
        ));
		//返回
		$json['html'] = "<form name='listForm'>" . $li . "</form>" . $page['button'] . clear;
		return json_encode($json, 320);
	}
    /**
     * 保存并提交
     * @return bool|string
     */
    public function saveAndCommit(): bool|string
    {
        $resultJson = $this->editEdit();
        $result = json_decode($resultJson,true);
        if ($result['warn'] == 2){
            unset($_SESSION['warn']);
            $resultJson = $this->commitEdit();
        }
        return $resultJson;
    }
	/**
	 * 编辑页
	 *
	 * @return string
	 */
	public function edit(): string
	{
		$id       = $this->get('id');
		$info     = query(self::table, " coid = '" . self::$coid . "' AND id = '" . $id . "' ");
		$button[] = [
			'style' => 'li-btn-blue-bg',
			"name"  => "保存",
			"type"  => "点击事件",
			"title" => "保存",
			'fun'   => "subForm('" . self::page . "EditForm','" . root . "control/adIndex.html?cla=" . self::page . "&fun=editEdit')",
		];
        $button[] = [
            "name" => "保存并提交",
            "type" => "点击事件",
            "title" => "保存",
            'fun' => "subForm('" . self::page . "EditForm','" . root . "control/adIndex.html?cla=" . self::page . "&fun=saveAndCommit')"
        ];
		$tr[]     = ['', '物料编码', '物料名称', '规格型号', '单位', '<div class="warehouse">' . '仓库' . inStockOtherClass::chooseWarehouse('mxWarehouseId') . '</div>', '入库数量', '批号', '单价（' . static::$unit . '）', '金额（' . static::$unit . '）', '材料费用分摊', '拆解费用分摊', '备注'];
		$result   = find(['table' => self::tableMx, 'where' => "orderId = '$info[id]' order by list"]);
        $totalArr = ['mxNum'=>0,'materialFee'=>0,'dismantleFee'=>0,'total'=>0];
		foreach ((array)$result['array'] as $k=>$array) {
			$material     = query('material', "id = '$array[materialId]'");
			$select       = select([
			    'name' => 'mxUnit[]',
                'option' => inventoryBalanceClass::materialUnit($array['materialId']),
                'value' => $array['unit']
            ]);
			$warehouseSel = idSelect([
			    'name' => 'mxWarehouseId[]',
                'sqlForm' => "warehouse WHERE coid = '" . self::$coid . "' AND state = '启用' ",
                'sqlId' => 'id',
                'sqlField' => "name",
                'title' => '仓库',
                'value' => $array['warehouseId']
            ]);
			$tr[]         =
				[
                    componentClass::tablePperation($k+1,"delTableRow(this);calculateTotal()").
					hidden(['name' => 'mxId[]', 'value' => $array['id']]) .
					hidden(['name' => 'mxMaterialId[]', 'value' => $array['materialId'],]),
					$material['code'],
					$material['name'],
					$material['model'],
					$select,
					$warehouseSel,
					text(['name' => 'mxNum[]', 'other' => self::digitalFiltering('numPrecision'), 'value' => self::lostZero($array['num'],'numPrecision'), 'blur' => 'countPrice']),
					text(['name' => 'mxBatch[]', 'value' => $array['batch']]),
                    text(['name' => 'mxPrice[]', 'other' => self::digitalFiltering('pricePrecision'), 'value' => self::lostZero($array['price'],'pricePrecision'), 'blur' => 'countMoney']),
                    "<span class='total'>" . self::formattingFigure($array['num'] * $array['price']) . "</span>",
                    text(['name' => 'materialFee[]', 'other' => self::digitalFiltering(), 'value' => self::lostZero($array['materialFee']), 'blur' => 'countPrice']),
                    text(['name' => 'dismantleFee[]', 'other' => self::digitalFiltering(), 'value' => self::lostZero($array['dismantleFee']), 'blur' => 'countPrice']),
					text(['name' => 'mxText[]', 'class' => "text", 'value' => $array['text'], 'blur' => 'countMoney'])
				];
            $totalArr['mxNum'] += $array['num'];
            $totalArr['materialFee'] += $array['materialFee'];
            $totalArr['dismantleFee'] += $array['dismantleFee'];
            $totalArr['total'] += self::formattingFigure($array['num'] * $array['price']);
		}
        $total = [
            6 => "<span id='total_mxNum'>".self::lostZero($totalArr['mxNum'],'numPrecision')."</span>",
            8 => "<span id='total_materialFee'>".self::lostZero($totalArr['materialFee'])."</span>",
            9 => "<span id='total_dismantleFee'>".self::lostZero($totalArr['dismantleFee'])."</span>",
            11 => "<span id='total_money'>".self::lostZero($totalArr['total'])."</span>",
        ];
        $table  = $this->listTable(array('tr' => $tr, 'end' => true, 'total' => $total));
		$page  = self::page;
        $but = <<<EOT
		    <span class="smallButton" onclick="layer('{$this->get('cla')}','addMx', $('form[name={$page}EditForm]').serialize())">选择物料</span>
		EOT;
        $info['warehouse'] = $info['warehouse']?:'未选择';
        $info['position'] = $info['position']?:'未选择';
        $info['batch'] = $info['batch']?:'未选择';
		//表单
        $data['button'] = $this->tableShowButton($button);
        $body = $this->edit4([
            '基本信息' => [
                [
                    must . '组合件' => hidden(['name' => 'materialId', 'value' => $info['materialId']]) .
                        '<span id="materialName">' . ($info['materialId'] ? self::materialName($info['materialId'])['name'] : '未选择') . '</span>' .
                        "<span class='del-row-button m-l-10' onclick=\"layer('{$this->get('cla')}','addMaterial',$('form[name={$page}EditForm]').serialize())\">选择</span>",
                    must . '仓库'   => "<span id='warehouse'>{$info['warehouse']}</span>" .
                        hidden(['name' => 'warehouseId', 'value' => $info['warehouseId'],]).
                        hidden(['name' => 'warehouse', 'value' => $info['warehouse'],]),
                    must . '仓位' => "<span id='position'>{$info['position']}</span>".
                        hidden(['name' => 'position', 'value' => $info['position'],]).
                        hidden(['name' => 'positionId', 'value' => $info['positionId'],]),
                    must . '批号' => "<span id='batch'>{$info['batch']}</span>".
                        hidden(['name' => 'batch', 'value' => $info['batch'],]),
                ],
                [
                    must . '拆解数量' => text([
                        'name' => "num",
                        'class' => 'text',
                        'other' => self::digitalFiltering('numPrecision'),
                        'blur' => 'countMaterialCost',
                        'value' => self::lostZero($info['num'],'numPrecision')
                    ]),
                    '出库单价' => "<span id='inventoryPrice'>".self::lostZero($info['inventoryPrice'],'pricePrecision')."</span>".
                        hidden(['name' => 'inventoryPrice', 'value' => $info['inventoryPrice'],]),
                    '材料费用' => "<span id='materialCost'>".self::lostZero($info['materialCost'])."</span>".
                        hidden(['name' => 'materialCost', 'value' => $info['materialCost'],]),
                    '拆解费用' => text(['name' => "fee", 'class' => 'text', 'other' => self::digitalFiltering(), 'value' => self::lostZero($info['fee'])]),
                ],
                [
                    must . '单据日期' => text(['name' => "orderDate", 'class' => 'text', 'value' => $info['orderDate'] ?: $this->date, 'laydate' => [],]),
                ],
                [
                    '备注'   => textarea(['name' => "text", 'class' => 'text', 'value' => $info['text']]),
                ],
            ]
        ]);
        $body .= $this->editList([
            'id' => 'materialTable',
            'title' => '选择明细',
            'button' => $but,
            'html' => $table,
        ]);
		$data['html'] = $this->pageEdit([
			"html"  => $body,
			'hidden' => hidden(['name' => 'id', 'value' => $id]),
		]);
		$data['html'] .= <<<EOT
		<script>
		//计算金额，税额等
        function countPrice(e){
            let obj = $(e).parent().parent()
            let materialFee = obj.find('[name="materialFee[]"]').val()*1,
                dismantleFee = obj.find('[name="dismantleFee[]"]').val()*1,
                mxNum = obj.find('[name="mxNum[]"]').val()*1
            
            let price = mxNum===0||mxNum===''?0:(materialFee+dismantleFee)/mxNum
            obj.find("[name='mxPrice[]']").val(price.toFixed(publicSettings.pricePrecision.num))
            countMoney(e)
        }
		//获取账面库存
		function addRow(){
		    let materialCost = $("[name='materialCost']").val()
		    let fee = $("[name='fee']").val()
			$.post(root+'control/adIndex.html?cla={$this->get('cla')}&fun=addMxEdit',$("form[name='mxForm']").serialize()+'&materialCost='+materialCost+'&fee='+fee,function(res) {
				$("#materialTable tbody").append(res.html);
				resetNumber($("#materialTable"))
			},'json');
		}
        function addMaterial(){
            $.post(root+'control/adIndex.html?cla={$this->get('cla')}&fun=addMaterialEdit', $("form[name='mxForm']").serialize(),function(resp) {
	         if (resp.warn == 2){
	            $('#dismantleAddMaterial').hide();
                $("[name='materialId']").val(resp.res.materialId);
	            $("#materialName").html(resp.res.name);
	            $("[name='warehouseId']").val(resp.warehouse.id);
	            $("[name='warehouse']").val(resp.warehouse.name);
	            $("[name='positionId']").val(resp.position.id);
	            $("[name='position']").val(resp.position.name);
	            $("[name='batch']").val(resp.batch);
	            $("[name='inventoryPrice']").val(resp.unitPrice);
	            $('#warehouse').text(resp.warehouse.name);
	            $('#position').text(resp.position.name);
	            $('#batch').text(resp.batch);
	            $('#inventoryPrice').text(resp.unitPrice);
	            countMaterialCost()
	         }else{
	             msg(res.warn);
	         }
	        },'json');
        }
        function countMaterialCost(){
	        let num = $('[name="num"]').val()*1,
	            price = $('[name="inventoryPrice"]').val()*1
	        let total = num * price
	        $("#materialCost").text(total.toFixed(amountPrecision))
	        $("[name='materialCost']").val(total.toFixed(amountPrecision))
	        calculateTotal()
	    }
        //计算金额，税额等
        function countMoney(e){
            let obj = $(e).parent().parent()
            let num = obj.find('[name="mxNum[]"]').val(),
                price = obj.find('[name="mxPrice[]"]').val()
            let total = num * price
            obj.find(".total").html(total.toFixed(amountPrecision))
            calculateTotal()
        }
        //计算总数量
        function calculateTotal(){
            let table = $('.editList')
            let num = 0,
            materialFee = 0,
            dismantleFee = 0,
            money = 0
            table.find("[name='mxNum[]']").each(function(index){
                if($(this).val()){
                  num+=Number($(this).val());
                }
                var materialFeeVal = table.find("[name='materialFee[]']").eq(index).val()
                if(materialFeeVal){
                    materialFee+=Number(materialFeeVal);
                }
                var dismantleFeeVal = table.find("[name='dismantleFee[]']").eq(index).val()
                if(dismantleFeeVal){
                    dismantleFee+=Number(dismantleFeeVal);
                }
                var totalText = table.find(".total").eq(index).text()
                if(totalText){
                    money+=Number(totalText);
                }
            })
            $("#total_mxNum").text(num.toFixed(publicSettings.numPrecision.num));
            $("#total_materialFee").text(materialFee.toFixed(amountPrecision));
            $("#total_dismantleFee").text(dismantleFee.toFixed(amountPrecision));
            $("#total_money").text(money.toFixed(amountPrecision));
        }
		</script>
EOT;
		//返回
		return $this->tab($data);
	}

	/**
	 *选择生产产品
	 *
	 * @return bool|string
	 */
	public function addMaterial(): bool|string
	{
		$html   =
            selectMultiple(array('name' => 'warehouse', 'title' => '仓库', 'table' => 'warehouse', 'where' => " coid = '" . self::$coid . "' AND state = '启用' ", 'sqlId' => 'id', 'sqlField' => 'name')).
            text(array("name" => "position", "title" => "仓位")).
            text(array("name" => "code", "title" => "物料编码")) .
            text(array("name" => "materialName", "title" => "物料名称")) .
            materialClass::typeSelect(name: 'typeId') .
            text(array("name" => "batch", "title" => "批次")).
            hidden(['name' => 'materialId', 'value' => $this->post('materialId')]).
            hidden(['name' => 'positionId', 'value' => $this->post('positionId')]).
            hidden(['name' => 'batchChoice', 'value' => $this->post('batch')])
        ;
		$button = "<input style='margin-left: 5px' onclick=\"addMaterial()\" type='button' class='searchSub' value='提交'>";
		$html   = $this->search($html);
		return $this->layer(array("title" => "添加", "height" => 600, "width" => 1000, "html" => $html, "button" => $button));
	}

	/**
	 *添加物料
	 */
	public function addMaterialSearch(): bool|string
	{
        $where      = " 1=1 ";
        $concatId = [];
	    if($this->post('materialId')) {
            $concatId = [$this->post('positionId').'-'.$this->post('materialId').'-'.$this->post('batchChoice')];
            $where      .= " and concat(positionId,'-',materialId,'-',batch) not in ('" . implode("','", $concatId) . "')";
        }
        $and        = " AND coid = '" . self::$coid . "' ";
        $mwhere = search([
            "like" => [
                'code' => $this->post('code'),
                'name' => $this->post('materialName'),
                'typePath' => $this->post('typeId'),
            ],
        ]);
        if ($mwhere) {
            $where .= " AND materialId IN (SELECT id FROM material WHERE coid = '" . self::$coid . "' $mwhere )  ";
        }
        $like       = [
            'batch' => $this->post('batch'),
        ];
        $equal      = [
            'warehouseId' => $this->post('warehouse')
        ];
        if ($this->post('position')) {
            $where .= " AND positionId IN (SELECT id FROM warehouse_position WHERE coid = '" . self::$coid . "' and name like '%".$this->post('position')."%')  ";
        }
        $where .= search([
                "like" => $like,
                "equal" => $equal,
            ]).$and;
        $fieldArr = self::resolveField([
            'field' => '`id`, `coid`, `warehouseId`, `positionId`, `materialId`, batch, SUM(num) as num, `time`',
            'group' => 'positionId,materialId,batch',
        ]);
        $where .= $fieldArr['group']." having sum(num)>0";
        $page = $this->page([
            "table" => 'inventory_record',
            'field' => $fieldArr['field'],
            "where" => $where,
            'pageNum' => 9,
            "order" => " time desc"
        ]);
        $json['sql'] = $page['sql'];
        //获取表头
        $checkAll = $this->checkAll("mxForm", "mxId");
        $tr[]     = ['','分类', '物料编码', '物料名称', '规格型号', '单位', '仓库', '仓位', '批号', '库存'];
        //获取记录
        foreach ($page['array'] as $array) {
            $mxId = $array['positionId'].'-'.$array['materialId'].'-'.$array['batch'];
            $material = query('material', " id = '$array[materialId]'");
            $tr[]     = [
                "<input name='mxId' value='$mxId' type='radio' class='radio-bigger'>",
                $material['typeName'],
                $material['code'],
                $material['name'],
                $material['model'],
                $material['unit'],
                warehouseClass::getName($array['warehouseId']),
                warehousePositionClass::getName($array['positionId']),
                $array['batch'],
                self::lostZero($array['num'],'numPrecision'),
            ];
        }
		$json['html'] = $page['hint'] . "<form name='mxForm'>" . $this->tableMany(array("tr" => $tr, "showSort" => true, "page" => $page['para'])) . "</form>" . $page['button'];
		return json_encode($json, 320);
	}

	/**
	 * 编辑
	 *
	 * @return bool|string
	 */
	public function addMaterialEdit(): bool|string
	{
		$mxId = $this->post('mxId');
		if (!$this->power(self::page, 'edit')) {
			$json['warn'] = '你还没有编辑权限';
		} elseif (empty($mxId)) {
			$json['warn'] = '请选择物料';
		} else {
		    $mxId = explode('-',$mxId);
            $warehouse_position = query('warehouse_position', "id = '$mxId[0]'",'id,name,orderId');
            $warehouse = query('warehouse', "id = '$warehouse_position[orderId]'",'id,name');
			$json = [
				'warn' => 2,
				'res'  => self::materialName($mxId[1]),
				'position'  => $warehouse_position,
				'warehouse'  => $warehouse,
				'batch'  => $mxId[2],
				'unitPrice'  => inventoryBalanceClass::unitPrice($mxId[1])
			];
		}
		return json_encode($json, 320);
	}

	/**
	 * 物料名称
	 *
	 * @param $materialId
	 * @return array
	 */
	public static function materialName($materialId): array
	{
		$material    = query('material', "id = '$materialId'");
		return [
			'name'          => $material['model'] . '-' . $material['name'],
			'materialId'    => $material['id'],
		];
	}

	public function editEdit()
	{
		$id               = $this->post('id') ?: self::getId();
		$mxIdArr          = $this->post('mxId') ?: [];
		$materialIdArr = $this->post('mxMaterialId');
		$mxUnitArr        = $this->post('mxUnit');
		$mxWarehouseIdArr = $this->post('mxWarehouseId');
		$mxNumArr         = $this->post('mxNum');
		$mxBatchArr       = $this->post('mxBatch');
		$mxPriceArr       = $this->post('mxPrice');
		$materialFeeArr  = $this->post('materialFee');
		$dismantleFeeArr  = $this->post('dismantleFee');
		$mxTextArr        = $this->post('mxText');

		$field      = [
			'warehouseId'   => $this->post('warehouseId'),
			'warehouse'     => $this->post('warehouse'),
			'materialId'    => $this->post('materialId'),
			'positionId' => $this->post('positionId'),
			'position' => $this->post('position'),
			'batch' => $this->post('batch'),
			'orderDate'     => $this->post('orderDate'),
			'num'           => $this->post('num'),
			'inventoryPrice'           => $this->post('inventoryPrice'),
			'materialCost'           => $this->post('materialCost'),
			'fee'           => $this->post('fee'),
			'text'          => $this->post('text'),
		];
		$annotation = [
			'warehouseId'   => '仓库名称',
			'warehouse'     => '仓库名称',
			'materialId'    => '组合件',
			'positionId' => '仓位',
			'position' => '仓位',
			'batch' => '批次',
			'orderDate'     => '单据日期',
			'num'           => '拆解数量',
			//			'fee'           => '费用',
			//			'text'          => '备注',
			//			'commitTime'    => '提交时间',
			//			'confirmTime'   => '确认时间',
			//			'passTime'      => '审核通过时间',
			//			'state'         => '状态',
		];
		$rules      = [
			'warehouseId'   => 'required',
			'warehouse'     => 'required',
			'materialId'    => 'required',
			'positionId' => 'required',
			'position' => 'required',
			'batch' => 'required',
			'orderDate'     => 'required|date',
            'num'           => 'required|numeric|min:1',
			//			'fee'           => 'required',
			//			'text'          => 'required',
			//			'commitTime'    => 'required',
			//			'confirmTime'   => 'required',
			//			'passTime'      => 'required',
			//			'state'         => 'required',
		];
        // 校验是否符合规则
		$vt     = new \verify();
		$result = $vt->setAliases($annotation)->validate($field, $rules)->isOk();
		if ($result === false) {
			$json['warn'] = $vt->getErrs()[0]; // 多个规则提示最前面一条
			goto resp;
		}
		$where = " coid = '" . self::$coid . "' AND id = '$id' ";
		$info  = query(self::table, $where);
		//判断
		if (!$this->power(self::page, "edit")) {
			$json['warn'] = "你没有编辑" . self::title . "的权限";
		} elseif (static::is_null_array($mxIdArr)) {
			$json['warn'] = '请选择拆解明细';
		} elseif (static::is_null_array($materialIdArr)) {
			$json['warn'] = '请选择拆解明细';
		} elseif (static::is_null_array($mxNumArr)) {
			$json['warn'] = '数量请填写完整';
        } elseif (static::is_null_array($mxBatchArr)) {
            $json['warn'] = '入库批号请填写完整';
		} elseif (static::is_null_array($mxWarehouseIdArr)) {
			$json['warn'] = '请选择拆解仓库';
		} elseif (static::is_null_array($mxPriceArr)) {
			$json['warn'] = '请选择单价';
		} /* elseif (static::is_null_array($dismantleFeeArr)) {
			$json['warn'] = '请输入拆解费用';
		} */ elseif (static::is_null_array($mxUnitArr)) {
            $json['warn'] = '请选择主单位';
        }elseif (self::formattingFigure(array_sum($materialFeeArr)) != self::formattingFigure(array_sum([$field['materialCost']]))) {
            $json['warn'] = '材料费用分摊不等于总的材料费用';
        }elseif (self::formattingFigure(array_sum($dismantleFeeArr)) != self::formattingFigure(array_sum([$field['fee']]))) {
            $json['warn'] = '拆解费用分摊不等于总的拆解费用';
		} elseif (!empty($info['id']) && $info['state'] == '已确认') {
			$json['warn'] = '此拆解单已确认，不能修改';
		} else {
			$this->startTrans();
			$isPass = true;//事务通过标志
			if (!$info['id']) {
				$orderNo      = codeTemplateClass::generateCode(self::page,[
                    'prefix' => 'CJ' . date('Ymd'),
                    'table'  => self::table,
                    'field'  => 'orderNo',
                    'where'  => " AND coid = '" . self::$coid . "' ",
                ],$field);
				$field        = array_merge($field, [
					'id'      => $id,
					'orderNo' => $orderNo,
					'state'   => '草稿',
					'coid'    => self::$coid,
					'stid'    => $this->control['stid'],
				]);
				$json['warn'] = static::insert(["table" => self::table, "field" => $field,]);
			} else {
				$json['warn'] = static::update([
					"table" => self::table,
					"field" => $field,
					"where" => $where,
				]);
			}
			//添加或更新报价单明细
			if (is_array($mxIdArr)) {
				foreach ($mxIdArr as $k => $nid) {
					$mx          = query(self::tableMx, "id = '$nid'");
					if (!empty($mx['id'])) {
						//更新
						$mxWarehouseIdArr = $this->post('mxWarehouseId');
						$mxNumArr         = $this->post('mxNum');
						$mxPriceArr       = $this->post('mxPrice');
						$dismantleFeeArr  = $this->post('dismantleFee');

						$warn = static::update([
							"table" => self::tableMx,
							"field" => [
								'coid'          => self::$coid,
								'materialId'    => $materialIdArr[$k],
								'warehouseId'   => $mxWarehouseIdArr[$k],
								'num'           => self::formattingFigure($mxNumArr[$k],'numPrecision'),
								'batch'           => $mxBatchArr[$k],
								'unit'          => $mxUnitArr[$k],
								'price'         => self::formattingFigure($mxPriceArr[$k],'pricePrecision'),
								'materialFee'  => self::formattingFigure($materialFeeArr[$k]),
								'dismantleFee'  => self::formattingFigure($dismantleFeeArr[$k]),
								'text'          => $mxTextArr[$k],
							],
							"where" => " id = '$nid'",
						]);
					} else {
						//新增
						$warn = static::insert([
							"table" => self::tableMx,
							"field" => [
								'id'            => $nid,
								'coid'          => self::$coid,
								'orderId'       => $id,
                                'materialId'    => $materialIdArr[$k],
								'warehouseId'   => $mxWarehouseIdArr[$k],
								'unit'          => $mxUnitArr[$k],
                                'num'           => self::formattingFigure($mxNumArr[$k],'numPrecision'),
                                'batch'           => $mxBatchArr[$k],
                                'price'         => self::formattingFigure($mxPriceArr[$k],'pricePrecision'),
                                'materialFee'  => self::formattingFigure($materialFeeArr[$k]),
                                'dismantleFee'  => self::formattingFigure($dismantleFeeArr[$k]),
								'text'          => $mxTextArr[$k],
							],
						]);
					}
					if (!in_array($warn, ['新增成功', '更新成功'])) {
						$isPass       = false;
						$json['warn'] = $warn;
						break;
					}
				}
			}
			if (in_array($json['warn'], ["新增成功", "更新成功"]) && $isPass) {
				$this->commitTrans();
				delete(['table' => self::tableMx, 'where' => " id not in ('" . implode("','", $mxIdArr) . "') and orderId = '$id'",]);
				//添加日志
				$type = mb_substr($json['warn'], 0, 2, 'utf-8');
				$text = $this->control['name'] . $type . "了" . self::title . " id：【" . $id . '】';
				$this->logText(["type" => self::page, "text" => $text]);
				//返回
				$_SESSION['warn'] = $json['warn'];
				$json['warn']     = 2;
				$json['href']     = root . "control/adIndex.html?cla=" . $this->get('cla') . "&fun=detail&id=" . $id;
			} else {
				$this->rollback();
			}
		}

		resp:
		return json_encode($json, 320);
	}


	/**
	 * @return bool|string
	 */
	public function addMx()
	{
		$callback = $this->post('callback') ? $this->post('callback') : self::page;
		$tableMx  = $this->post('tableMx');
		$html     =
			text(["name" => "type", "title" => "分类"])
			. text(["name" => "code", "title" => "物料编码"])
			. text(["name" => "name", "title" => "物料名称"])
			. text(["name" => "model", "title" => "规格型号"])
            .'&nbsp;&nbsp;'.checkbox(["name"    => "bom","value"   => [1=>'bom清单'],'checked' => '',])
			. hidden(["name" => "state", 'value' => $this->post('state') ?? '在库'])
			. hidden(["name" => "tableMx", 'value' => $tableMx])
			. hidden(["name" => "mxMaterialId", 'value' => implode(',',(array)$this->post('mxMaterialId'))])
			. hidden(["name" => "materialId", 'value' => implode(',',(array)$this->post('materialId'))])
			. hidden(['name' => 'orderId', 'value' => $this->post('orderId')]);
		$button   = "<input style='margin-left: 5px' onclick=\"addRow();$('#" . self::page . "AddMx').remove()\" type='button' class='searchSub' value='提交'>";
		$html     = $this->search($html);
		return $this->layer(["title" => "添加", "height" => 600, "width" => 1100, "html" => $html, "button" => $button]);
	}

	/**
	 *添加物料
	 */
	public function addMxSearch()
	{
		$materialId = $this->post('mxMaterialId') ? explode(',', $this->post('mxMaterialId')) : [];
		$where      = " 1=1 and a.coid = '" . self::$coid . "' and a.id not in ('" . implode("','", $materialId) . "')";
        //查询bom清单下的物料
        if(!static::isNull($this->post('bom'))){
            $bom = query('bom', "coid = '" . self::$coid . "' and materialId = '".$this->post('materialId')."' and isDefault = 1 and state = '启用'");
            if($bom['id']) {
                $material = query("material"," id = '".$this->post('materialId')."' ","unit");
                $bomMx = machiningOrderClass::bomMx($bom['id'],$this->post('materialId'),1,$material['unit']);
                $ids = array_column($bomMx,'materialId');
                $where .= " and a.id in ('" . implode("','", $ids) . "') ";
            }
        }
		$like       = [
			'a.name' => $this->post('materialName'),
			'code'   => $this->post('code'),
			'model'  => $this->post('model'),
		];
		$equal      = [
			'a.state'  => '启用',
			'a.typeName' => $this->post('type'),
		];
		$where      .= search(["like" => $like, "=" => $equal]);
		$page       = $this->page([
			"table"   => "material as a",
			"field"   => "a.*",
			"where"   => " {$where} ",
			'pageNum' => 50,
			"order"   => "a.`time` ASC",
		]);
		//获取表头
		$checkAll = $this->checkAll("mxForm", "mxId");
		$tr[]     = [$checkAll, '分类', '物料编码', '物料名称', '规格型号'];
		//获取记录
		foreach ($page['array'] as $array) {
			$dominate = [
				"box" => ["name" => "mxId", "value" => $array['id']],
			];
			$tr[]     = [
				$this->dominate($dominate),
                $array['typeName'],
				$array['code'],
				$array['name'],
				$array['model'],
			];
		}
		$json['html'] = $page['hint'] .
            "<form name='mxForm'>".
                hidden(['name'=>'materialId','value'=>$this->post('materialId')]) .
                hidden(['name'=>'mxMaterialId','value'=>implode(",", $materialId)]) .
                $this->tableMany(array("tr" => $tr, "showSort" => true, "page" => $page['para'])) .
            "</form>" .
            $page['button'];
		return json_encode($json, 320);
	}

	/**
	 * 编辑
	 *
	 * @return bool|string
	 */
	public function addMxEdit()
	{
		$mxIdArr = $this->post('mxId');
		if (!$this->power(self::page, 'edit')) {
			$json['warn'] = '你还没有编辑权限';
		} elseif (empty($mxIdArr) || !is_array($mxIdArr)) {
			$json['warn'] = '请选择物料';
		} else {
			$tr = [];
			$mxMaterialId = $this->post('mxMaterialId');
			//bom清单
            $bom = query('bom', "coid = '" . self::$coid . "' and materialId = '".$this->post('materialId')."' and isDefault = 1 and state = '启用'");
            if($bom['id']) {
                $material = query("material"," id = '".$this->post('materialId')."' ");
                $bomMx = machiningOrderClass::bomMx($bom['id'],$this->post('materialId'),1,$material['unit']);
                $ids = array_column($bomMx,'num','materialId');
            }
            $batch = inStockClass::getBatchNo('拆解出库');
			foreach ($mxIdArr as $k=>$mxId) {
				$material     = query('material', "id = '$mxId'");
				$id           = self::getId();
				$select       = select(['name' => 'mxUnit[]', 'value' => $material['unit'], 'option' => inventoryBalanceClass::materialUnit($material['id'])]);
				$warehouseSel = idSelect([
				    'name' => 'mxWarehouseId[]',
                    'sqlForm' => "warehouse WHERE coid = '" . self::$coid . "' AND state = '启用' ",
                    'sqlId' => 'id',
                    'sqlField' => "name",
                    'title' => '仓库'
                ]);
				$num = isset($ids[$material['id']])?self::lostZero($ids[$material['id']],'numPrecision'):'';
                $materialFee = '';
                $dismantleFee = '';
				if($k == 0 && empty($mxMaterialId)){
                    $materialFee = self::lostZero($this->post('materialCost'));
                    $dismantleFee = self::lostZero($this->post('fee'));
                }
                $tr[]              = [
                    componentClass::tablePperation('',"delTableRow(this);calculateTotal()").
                    hidden(array('name' => 'mxId[]', 'value' => $id)) .
                    hidden(array('name' => 'mxMaterialId[]', 'value' => $mxId)),
                    $material['code'],
                    $material['name'],
                    $material['model'],
                    $select,
                    $warehouseSel,
                    text(array('name' => 'mxNum[]', 'type' => 'text', 'blur' => 'countPrice', 'other' => self::digitalFiltering('numPrecision'), 'value' => $num)),
                    text(array('name' => 'mxBatch[]', 'value' => $batch)),
                    text(array('name' => 'mxPrice[]', 'type' => 'text', 'blur' => 'countMoney', 'other' => self::digitalFiltering('pricePrecision'), 'value' => $dismantleFee)),
                    "<span class='total'>0</span>",
                    text(array('name' => 'materialFee[]', 'type' => 'text', 'blur' => 'countPrice', 'other' => self::digitalFiltering(), 'value' => $materialFee)),
                    text(array('name' => 'dismantleFee[]', 'type' => 'text', 'blur' => 'countPrice', 'other' => self::digitalFiltering(), 'value' => $dismantleFee)),
                    text(array('name' => 'mxText[]', 'class' => 'text')),
                ];
			}
            $json['html'] = $this->tableMany(array('tr' => $tr, 'thead' => false));
			$json['warn'] = 2;
		}
		return json_encode($json, 320);
	}


	/*详情页*/
	public function detail(): string
	{
		$info = query(self::table, " coid = '" . self::$coid . "' AND id = '{$this->get('id')}'");
		if (empty($info['id'])) {
			$html = '未找到此' . self::title;
		} else {
			//菜单
			$data   = array(
				"id" => $info['id'],
			);
			$button = [];
			if ($this->power(self::page, "edit") && $info['state'] != '已确认') {
				if ($info['state'] == '草稿') {
					//按钮
					$button[] = [
						"name"  => "编辑",
						"type"  => "顶部页卡",
						"title" => "编辑用户",
						"url"   => $this->root . "control/adIndex.html?cla={$this->get('cla')}&fun=edit&id=" . $info['id'],
						'style' => 'li-btn-blue-bg',
					];
					//按钮
					$button[] = [
						"name" => "提交",
						"type" => "弹出层",
						"cla"  => $this->get('cla'),
						"fun"  => "operate",
						"post" => ["act" => 'commit', "id" => $info['id']],
					];
				}
				//按钮
				$button[] = [
					"name" => "删除",
					"type" => "弹出层",
					"cla"  => $this->get('cla'),
					"fun"  => "operate",
					"post" => ["act" => 'del', "id" => $info['id']],
				];
			}
			if ($this->power(self::page, "confirm") && $info['state'] == '待确认') {
				$button[] = [
					"name"  => "确认",
					"type"  => "弹出层",
					"cla"   => $this->get('cla'),
					"fun"   => "operate",
					"post"  => ["act" => 'confirm', "id" => $info['id']],
					'style' => 'li-btn-blue-bg',
				];
			}
			if ($this->power(self::page, "confirm") && $info['state'] == '待确认') {
				$button[] = [
					"name" => "取消",
					"type" => "弹出层",
					"cla"  => $this->get('cla'),
					"fun"  => "operate",
					"post" => ["act" => 'cancel', "id" => $info['id']],
				];
			}
			//操作记录
            $button[] = self::operateLogBut($info['id']);

            $totalArr = ['num'=>0,'money'=>0,'materialFee'=>0,'dismantleFee'=>0];
			$mxtr[] = ['物料编码', '物料名称', '规格型号', '单位', '仓库', '入库数量', '批号', '单价（' . static::$unit . '）', '金额（' . static::$unit . '）', '材料费用分摊（' . static::$unit . '）', '拆解费用分摊（' . static::$unit . '）', '备注'];
			$result = find(array('table' => self::tableMx, 'where' => "orderId = '$info[id]' order by list"));
			foreach ($result['array'] as $array) {
				$material    = query('material', " id = '$array[materialId]'");
				$mxtr[]      = [$material['code'], $material['name'], $material['model'], $array['unit'], warehouseClass::getName($array['warehouseId']), self::lostZero($array['num'],'numPrecision'), $array['batch'], self::lostZero($array['price'],'pricePrecision'), self::formattingFigure($array['num'] * $array['price']), self::lostZero($array['materialFee']), self::lostZero($array['dismantleFee']), $array['text']];
                $totalArr['num'] += $array['num'];
                $totalArr['money'] += self::formattingFigure($array['num'] * $array['price']);
                $totalArr['materialFee'] += $array['materialFee'];
                $totalArr['dismantleFee'] += $array['dismantleFee'];
			}
            $total_tr = [
                5=>self::lostZero($totalArr['num'],'numPrecision'),
                8=>self::lostZero($totalArr['money']),
                9=>self::lostZero($totalArr['materialFee']),
                10=>self::lostZero($totalArr['dismantleFee']),
            ];
			$material    = query('material', "id = '{$info['materialId']}'");
			//生成表单
            $data['button'] = $this->tableShowButton($button);
			$data['html'] = $this->tableShow([
				'详细信息' => [
					[
						"组合件" => $material['model'] . '-' . $material['name'],
						"仓库"   => $info['warehouse'],
						"仓位" => $info['position'],
						"批号" => $info['batch'],
					],
                    [
                        "拆解数量" => self::lostZero($info['num'],'numPrecision'),
                        "单据日期" => $info['orderDate'],
                        '材料单价（' . static::$unit . '）' => self::lostZero($info['inventoryPrice'],'pricePrecision'),
                        '材料费用（' . static::$unit . '）' => self::lostZero($info['materialCost']),
                    ],
					[
                        '拆解费用（' . static::$unit . '）' => self::lostZero($info['fee']),
						"单据编号" => $info['orderNo'],
						"制单人"  => self::findStaff($info['stid']),
						"状态"   => $info['state']
					],
                    [
                        "备注"                 => pre($info['text']),
                    ],
				]
			]);
            $data['html'] .= $this->detailList([
                'title' => '子件',
                'html' => $this->listTable(['tr' => $mxtr, 'showSort' => true, 'total' => $total_tr]),
            ]);
			//生成页面
			$html = $this->tab($data);
		}
		//返回
		return $html;
	}

	/**
	 * 确认
	 */
	public function confirmEdit(): string
	{
		$id    = $this->post('id');
		$info  = query(self::table, " coid = '" . self::$coid . "' AND id = '$id'");
		$field = [
			'state'       => '已确认',
			//			'checkId'     => self::$stid,
			'confirmTime' => $this->time,
		];
        /***仓库允许零库存出库*/
        $outAllowZero = optionSettingClass::getSettingItem('库存','outAllowZero');
		if (!$this->power(self::page, 'confirm')) {
			$json['warn'] = '你还没有确认权限';
		} else {
			$this->startTrans();
			if (empty($info['id'])) {
				$json['warn'] = '未找到此拆解单';
			} else {
				if ($info['state'] != '待确认') {
					$json['warn'] = '此拆解单不是待确认状态，不能确认';
				} else {
					$isPass       = true; // 事务通过标志
					$json['warn'] = update([
						"table" => self::table,
						"field" => $field,
						"where" => "id = '$info[id]'",
					]);
					if (in_array($json['warn'], ["新增成功", "更新成功"]) && $isPass === true) {
						$details = find([
							'table' => self::tableMx,
							'where' => " orderId = '{$info['id']}'",
						]);
						foreach ($details['array'] as $key => $value) {
                            //检查物料的入库批次是否使用过
                            $warn = inStockClass::batchCheck($value['materialId'],[$value['batch']]);
                            if($warn !== true){
                                $json['warn'] = $warn;
                                goto resp;
                            }
                            $material = query("material"," id = '".$value['materialId']."' ");
                            if(empty($material['positionId']) || $value['warehouseId'] != $material['warehouse']) {
                                $material['positionId'] = inventoryBalanceClass::matchLocation($value['warehouseId']);
                                $material['warehouse'] = $value['warehouseId'];
                            }
							// 转换主单位
							$mainUnitNum = inventoryBalanceClass::toMainUnit($value['materialId'], $value['num'], $value['unit']);
                            $bool = inventoryBalanceClass::inventoryControl($value['materialId'], $mainUnitNum, "top");  //最高库存控制
                            if($bool !== true){
                                $json['warn'] = $bool;
                                goto resp;
                            }
                            //单位单价转换
                            $price = round((float)$value['num']*(float)$value['price']/(float)$mainUnitNum,4);
                            inventoryDefaultClass::recordInventoryPrice($value['materialId'],$mainUnitNum,$price);//计算记录加权平均单价
                            $changeId               = self::getId();
                            $fieldChange            = [
                                'id'               => $changeId,
                                'coid'             => self::$coid,
                                'type'             => '其他入库',
                                'classify'         => 1,
                                'targetId'         => '',
                                'sourceTargetName' => '',
                                'confirmTime'      => $this->time,
                                'reviewTime'       => $this->time,
                                'state'            => '已复核',
                                'stid'             => self::$stid,
                            ];
                            $userNo                 = codeTemplateClass::generateCode('inStock', [
                                'prefix' => 'RKD' . date('Ymd'),
                                'table'  => 'inventory_changes',
                                'field'  => 'orderNo',
                                'where'  => " and coid = '" . self::$coid . "'",
                                'index'  => $key + 1,
                            ], $fieldChange);
                            $fieldChange['orderNo'] = $userNo;
                            $warn                   = static::insert(array(
                                'table' => 'inventory_changes',
                                'field' => $fieldChange,
                            ));
                            if ($warn != '新增成功') {
                                $json['warn'] = "新增入库变动失败";
                                goto resp;
                            }
                            //生成出库变动记录
                            $warn     = static::insert(array(
                                'table' => 'inventory_changes_detail',
                                'field' => $fieldChangeMx = [
                                    'id'            => self::getId(),
                                    'coid'          => self::$coid,
                                    'orderId'       => $changeId,
                                    'materialId'    => $value['materialId'],
                                    'orderNum'      => $mainUnitNum,
                                    'batch'         => $value['batch'],
                                    'num'           => $mainUnitNum,
                                    'unit'          => $material['unit'],
                                    'price'         => $price,
                                    'money'         => self::formattingFigure($price * $mainUnitNum),
                                    'sourceTable'   => '',
                                    'sourceId'      => '',
                                    'sourceNo'      => '',
                                    'warehouseId'   => $material['warehouse'],
                                    'positionId'    => $material['positionId'],
                                ],
                            ));
                            if ($warn != '新增成功') {
                                $json['warn'] = "新增出库变动明细失败";
                                goto resp;
                            }
                            $recordId = self::getNo();
							// 材料入库
							insert([
								'table' => self::tableRecord,
								'field' => [
									'id'            => $recordId,
									'coid'          => self::$coid,
									'warehouseId'   => $material['warehouse'],
                                    'positionId'    => $material['positionId'],
									'materialId'    => $value['materialId'],
                                    'batch' => $value['batch'],
									'num'           => $mainUnitNum,
                                    'changesId'        => $fieldChangeMx['id'],
                                    'defaultPrice'        => $price,
								],
							]);
                            if(!empty($material['positionId']))inventoryBalanceClass::recordStockToLocation($recordId,['positionId'=>$material['positionId']]);
						}
						// 组合件出库
                        $mainUnitNum = inventoryBalanceClass::toMainUnit($info['materialId'], $info['num']);
                        // 判断库存
                        if (!$outAllowZero && inventoryBalanceClass::inventoryNum($info['materialId'], $info['warehouseId'],$info['positionId'],$info['batch']) - $mainUnitNum < 0) {
                            $material = query("material"," id = '$info[materialId]' ");
                            $json['warn'] = '组合件【'.$material['name'].'】出库数量不能大于库存数量';
                            goto resp;
                        }
                        $bool = inventoryBalanceClass::inventoryControl($info['materialId'], $mainUnitNum, "down");  //最低库存控制
                        if($bool !== true){
                            $json['warn'] = $bool;
                            goto resp;
                        }
                        $changeId               = self::getId();
                        $fieldChange            = [
                            'id'               => $changeId,
                            'coid'             => self::$coid,
                            'type'             => '其他出库',
                            'classify'         => 0,
                            'targetId'         => '',
                            'sourceTargetName' => '',
                            'confirmTime'      => $this->time,
                            'reviewTime'       => $this->time,
                            'state'            => '已复核',
                            'stid'             => self::$stid,
                        ];
                        $userNo                 = codeTemplateClass::generateCode('outStock', [
                            'prefix' => 'CKD' . date('Ymd'),
                            'table'  => 'inventory_changes',
                            'field'  => 'orderNo',
                            'where'  => " and coid = '" . self::$coid . "'",
                        ], $fieldChange);
                        $fieldChange['orderNo'] = $userNo;
                        $warn                   = static::insert(array(
                            'table' => 'inventory_changes',
                            'field' => $fieldChange,
                        ));
                        if ($warn != '新增成功') {
                            $json['warn'] = "新增出库变动失败";
                            goto resp;
                        }
                        //生成出库变动记录
                        $avgPrice = inventoryBalanceClass::unitPrice($info['materialId']);
                        $material = query("material"," id = '".$info['materialId']."' ","name,unit");
                        $warn     = static::insert(array(
                            'table' => 'inventory_changes_detail',
                            'field' => $fieldChangeMx = [
                                'id'            => self::getId(),
                                'coid'          => self::$coid,
                                'orderId'       => $changeId,
                                'materialId'    => $info['materialId'],
                                'orderNum'      => $mainUnitNum,
                                'batch'         => $info['batch'],
                                'num'           => $mainUnitNum,
                                'unit'          => $material['unit'],
                                'price'         => $avgPrice,
                                'money'         => self::formattingFigure($avgPrice * $mainUnitNum),
                                'sourceTable'   => '',
                                'sourceId'      => '',
                                'sourceNo'      => '',
                                'warehouseId'   => $info['warehouseId'],
                                'positionId'    => $info['positionId'],
                            ],
                        ));
                        if ($warn != '新增成功') {
                            $json['warn'] = "新增出库变动明细失败";
                            goto resp;
                        }
						insert([
							'table' => self::tableRecord,
							'field' => [
								'id'            => self::getNo(),
								'coid'          => self::$coid,
								'warehouseId'   => $info['warehouseId'],
                                'positionId'    => $info['positionId'],
								'materialId'    => $info['materialId'],
                                'batch'         => $info['batch'],
								'num'           => -1 * $mainUnitNum,
                                'changesId'        => $fieldChangeMx['id'],
                                'defaultPrice'        => $avgPrice,
							],
						]);
                        if(!empty($info['positionId']))
                        {
                            //判断库存是否用完，去掉入库id
                            inventoryBalanceClass::recordStockToLocation('',[
                                'materialId'=>$info['materialId'],
                                'warehouseId'=>$info['warehouseId'],
                                'positionId'=>$info['positionId'],
                                'batch'=>$info['batch']
                            ]);
                        }
						// 补出入库记录
						inventoryBalanceClass::otherToinventory(self::table, $id);
						$this->commitTrans(); //提交事务
						auditingFollow([
							"type"   => "拆解单",
							"typeId" => $info['id'],
							"text"   => "【{$this->control['name']}】确认",
						]);
						//添加日志
						$type = mb_substr($json['warn'], 0, 2, 'utf-8');
						$text = $this->control['name'] . $type . "了" . self::title . "id：【" . $id . '】';
						$this->logText(["type" => self::page, "text" => $text]);
						//返回
						$_SESSION['warn'] = $json['warn'];
						$json['warn']     = 2;
						$json['href']     = root . "control/adIndex.html?cla=" . $this->get('cla') . "&fun=detail&id=" . $info['id'];
					}
				}
			}
		}
		resp:
		return json_encode($json, 320);
	}

	/**
	 * 取消
	 */
	public function cancelEdit(): string
	{
		$id    = $this->post('id');
		$info  = query(self::table, " coid = '" . self::$coid . "' AND id = '$id'");
		$field = [
			'state'       => '草稿',
			'checkId'     => '',
			'confirmTime' => '',
		];
		if (!$this->power(self::page, 'cancel')) {
			$json['warn'] = '你还没有取消权限';
		} else {
			if (empty($info['id'])) {
				$json['warn'] = '未找到此拆解单';
			} /* elseif ($info['state'] != '已确认') {
            $json['warn'] = '此拆解单不是已确认状态，无需撤回';
        } elseif(static::total(['table'=>'purchase_order_detail','where'=>"sourceId in (select id from ".self::tableMx." where orderId = '$id') and coid = '".self::$coid."'"]) >0){
            $json['warn'] = '此申请单已在采购单中使用，暂不能撤回';
        }*/
			else {
				$json['warn'] = update([
					"table" => self::table,
					"field" => $field,
					"where" => "id = '$info[id]'",
				]);
				if (in_array($json['warn'], ["新增成功", "更新成功"])) {
					auditingFollow(array(
						"type"   => "拆解单",
						"typeId" => $info['id'],
						"text"   => "【{$this->control['name']}】取消",
					));
					//添加日志
					$type = mb_substr($json['warn'], 0, 2, 'utf-8');
					$text = $this->control['name'] . $type . "了" . self::title . "id：【" . $id . '】';
					$this->logText(["type" => self::page, "text" => $text]);
					//返回
					$_SESSION['warn'] = $json['warn'];
					$json['warn']     = 2;
					$json['href']     = root . "control/adIndex.html?cla=" . $this->get(
							'cla'
						) . "&fun=detail&id=" . $info['id'];
				}
			}
		}
		resp:
		return json_encode($json, 320);
	}

	/**
	 * 提交
	 */
	public function commitEdit(): string
	{
		$id    = $this->post('id');
		$info  = query(self::table, " coid = '" . self::$coid . "' AND id = '$id'");
		$field = [
			'state'      => '待确认',
			'commitTime' => $this->time,
		];
		if (!$this->power(self::page, 'edit')) {
			$json['warn'] = '你还没有编辑权限';
		} else {
			if (empty($info['id'])) {
				$json['warn'] = '未找到此拆解单';
			} else {
				if ($info['state'] != '草稿') {
					$json['warn'] = '此拆解单不是草稿状态，不能提交';
				} else {
					$json['warn'] = update(array(
						"table" => self::table,
						"field" => $field,
						"where" => "id = '$info[id]'",
					));
					if (in_array($json['warn'], ["新增成功", "更新成功"])) {
						auditingFollow([
							"type"   => "拆解单",
							"typeId" => $info['id'],
							"text"   => "【{$this->control['name']}】提交",
						]);
						//添加日志
						$type = mb_substr($json['warn'], 0, 2, 'utf-8');
						$text = $this->control['name'] . $type . "了" . self::title . "id：【" . $id . '】';
						$this->logText(["type" => self::page, "text" => $text]);
						//返回
						$_SESSION['warn'] = $json['warn'];
						$json['warn']     = 2;
						$json['href']     = root . "control/adIndex.html?cla=" . $this->get('cla') . "&fun=detail&id=" . $info['id'];
					}
				}
			}
		}
		resp:
		return json_encode($json, 320);
	}

	// 操作中转
	public function operate(): string
	{
		$act   = $this->post('act') ?? '';
		$pwd   = $word = false; // 需要密码
		$power = '';
		switch ($act) {
			case 'confirm':
				$act      = 'confirm';
				$msg      = '确认';
				$title    = '是否已确认此拆解单，确认后将不可修改？';
				$function = 'confirmEdit';
				$form     = self::page . 'OperateForm, detailForm';

				$word = true;
				break;
			case 'commit':
				$act      = 'edit';
				$msg      = '编辑';
				$title    = '是否确认提交此拆解单？';
				$function = 'commitEdit';
				$form     = self::page . 'OperateForm, detailForm';

				$word = true;
				break;
			case 'cancel':
				$act      = 'cancel';
				$msg      = '撤回';
				$title    = '是否确认取消此拆解单？';
				$function = 'cancelEdit';
				$form     = self::page . 'OperateForm, detailForm';

				$word = true;
				break;
			default:
				$act      = 'del';
				$msg      = '删除' . self::title;
				$title    = self::page . 'Delete';
				$function = 'delete';
				$form     = self::page . 'OperateForm, listForm, quoForm';

				break;
		}
		if (!$this->power(self::page, $act)) {
			$_SESSION['warn'] = '你还没有' . $msg . '的权限';
			$json             = [
				'warn' => 2,
				'href' => root . 'control/adIndex.html?cla=' . $this->get('cla') . '&fun=home',
			];
		} else {
			return $this->confirm([
				'title'    => $title,
				'function' => $function,
				'form'     => $form,
				'power'    => $power,
				'pwd'      => $pwd,
				'word'     => $word,
			]);
		}

		resp:
		return json_encode($json, 320);
	}

	/**
	 * 删除
	 *
	 * @return bool|string
	 */
	public function delete(): string|false
	{
		$array = $this->post('listId') ?? $this->post('id');
		if (!$this->power(self::page, "del")) {
			$json['warn'] = "你没有删除的权限";
		} else {
			if (empty($array)) {
				$json['warn'] = "你一个数据都没有选择呢";
			} else {
				$text  = "";
				$x     = 0;
				$array = is_array($array) ? $array : [$array];
				foreach ($array as $id) {
					$info = query(self::table, " id = '$id' ");
					if ($info['state'] == '已确认') {
						$warn = "删除失败：已确认，暂不能删除";
					} else {
						//最后删除基本参数
						delete(array("table" => self::table, "where" => " id = '$id' "));
						delete(array("table" => self::tableMx, "where" => " orderId = '$id' "));
						delete(array("table" => 'auditing_follow', "where" => " typeId = '$id' "));
						//返回
						$warn = "删除成功";
						$x++;
					}
					$text .= self::title . "ID【" . $info['id'] . "】" . $warn . "。<br>";
				}
				//添加日志
				$text = $this->control['name'] . "删除了" . self::title . "，结果如下：<br>" . $text;
				$this->logText(array("type" => self::page, "text" => $text));
				$_SESSION['warn'] = "删除了" . $x . "个" . self::title . "，详情见系统日志。";
				$json['warn']     = 2;
				$json['href']     = root . "control/adIndex.html?cla=" . $this->get('cla') . "&fun=home";
			}
		}
		return json_encode($json, 320);
	}

}
